package 网络编程.upload;

import 网络编程.utils.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName TCPFileUploadServer.java
 * @Description 文件上传的服务端
 * @createTime 2023年05月03日 17:57:00
 */
public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {
        //1.服务端在本机监听8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务端在8888端口监听");
        //2.等待连接
        Socket socket = serverSocket.accept();

        //3.读取客服端发送的数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //4.将得到bytes数组，写入到指定的路径，就得到一个文件了
        String destFilePath ="D:\\files\\f\\2.png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
        bos.write(bytes);

        //向客服端会回复"收到图片"
        //通过socket 获取到输出流（字符）

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write("收到图片");
        writer.flush();
        socket.shutdownOutput(); //设置写入结束标记
        writer.close();

        bis.close();
        socket.close();
        bos.close();
        serverSocket.close();

    }
}
